# \per\mnxc\survival_evolution\po\world.py
from collections import defaultdict

import numpy as np
import pygame

from per.mnxc.survival_evolution.constants.constants import WORLD_WIDTH, WORLD_HEIGHT
from per.mnxc.survival_evolution.po.organism import Organism, Plant
from per.mnxc.survival_evolution.po.space_grid import SpaceGrid


class World:
    def __init__(self, screen: pygame.Surface, width: int = WORLD_WIDTH, height: int = WORLD_HEIGHT):
        self.screen = screen
        self.width = width
        self.height = height
        self.space_grid = SpaceGrid((width, height))
        self.organisms: defaultdict[type[Organism], list[Organism]] = defaultdict(list)
        # 世界播放速度
        self.play_speed: float = 1
        rng = np.random.default_rng(1)
        # 初版-生态
        for x,y in rng.standard_normal((100, 2)):
            # 生成植物
            self.add_organism(Plant(self.width * x, self.height * y))

    def add_organism(self, organism: Organism):
        self.organisms[type(organism)].append(organism)
        self.space_grid.refresh_organism(organism)
    def remove_organism(self, organism: Organism):
        self.organisms[type(organism)].remove(organism)
        organism.is_alive = False
        self.space_grid.refresh_organism(organism)
    def update(self, delta_time: float):
        for organism_type in self.organisms:
            for organism in self.organisms[organism_type]:
                organism.update(delta_time, self.space_grid)
    # 绘制世界
    def draw(self):
        # 绘制背景
        self.screen.fill((0, 0, 0))
        for organism_type in self.organisms:
            for organism in self.organisms[organism_type]:
                organism.draw(self.screen)
